package org.br.erp.project.project.controller;

import java.io.UnsupportedEncodingException;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.br.erp.base.utils.ERPUtils;
import org.br.erp.project.expenseinfo.entity.Projectexpenseinfo;
import org.br.erp.project.expenseinfo.service.IProjectexpenseinfoService;
import org.br.erp.project.projecttask.entity.Projecttask;
import org.br.erp.project.projecttask.service.IProjecttaskService;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.vo.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.br.erp.project.project.entity.Projectitem;
import org.br.erp.project.project.entity.Projectplannedtime;
import org.br.erp.project.project.entity.Projectsalesitem;
import org.br.erp.project.project.entity.Projectpoitem;
import org.br.erp.project.project.entity.Projectexpense;
import org.br.erp.project.project.entity.Project;
import org.br.erp.project.project.vo.ProjectPage;
import org.br.erp.project.project.service.IProjectService;
import org.br.erp.project.project.service.IProjectitemService;
import org.br.erp.project.project.service.IProjectplannedtimeService;
import org.br.erp.project.project.service.IProjectsalesitemService;
import org.br.erp.project.project.service.IProjectpoitemService;
import org.br.erp.project.project.service.IProjectexpenseService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 项目
 * @Author: jeecg-boot
 * @Date:   2024-05-08
 * @Version: V1.0
 */
@Api(tags="项目")
@RestController
@RequestMapping("/project.project/project")
@Slf4j
public class ProjectController {
	@Autowired
	private IProjectService projectService;
	@Autowired
	private IProjectitemService projectitemService;
	@Autowired
	private IProjectplannedtimeService projectplannedtimeService;
	@Autowired
	private IProjectsalesitemService projectsalesitemService;
	@Autowired
	private IProjectpoitemService projectpoitemService;
	@Autowired
	private IProjectexpenseService projectexpenseService;

	@Autowired
	private IProjecttaskService projecttaskService;

	@Autowired
	private ISysBaseAPI sysBaseAPI;

	@Autowired
	private IProjectexpenseinfoService projectexpenseinfoService;
	
	/**
	 * 分页列表查询
	 *
	 * @param project
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "项目-分页列表查询")
	@ApiOperation(value="项目-分页列表查询", notes="项目-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<Project>> queryPageList(Project project,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<Project> queryWrapper = QueryGenerator.initQueryWrapper(project, req.getParameterMap());
		List<String> userByParentUser = sysBaseAPI.getUserByParentUser();
		queryWrapper.in("assignedto",userByParentUser);

		Page<Project> page = new Page<Project>(pageNo, pageSize);
		IPage<Project> pageList = projectService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param projectPage
	 * @return
	 */
	@AutoLog(value = "项目-添加")
	@ApiOperation(value="项目-添加", notes="项目-添加")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody ProjectPage projectPage) {
		Project project = new Project();
		BeanUtils.copyProperties(projectPage, project);
		projectService.saveMain(project, projectPage.getProjectitemList(),projectPage.getProjectplannedtimeList(),projectPage.getProjectsalesitemList(),projectPage.getProjectpoitemList(),projectPage.getProjectexpenseList());
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param projectPage
	 * @return
	 */
	@AutoLog(value = "项目-编辑")
	@ApiOperation(value="项目-编辑", notes="项目-编辑")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody ProjectPage projectPage) {
		Project project = new Project();
		BeanUtils.copyProperties(projectPage, project);
		Project projectEntity = projectService.getById(project.getId());
		if(projectEntity==null) {
			return Result.error("未找到对应数据");
		}
		projectService.updateMain(project, projectPage.getProjectitemList(),projectPage.getProjectplannedtimeList(),projectPage.getProjectsalesitemList(),projectPage.getProjectpoitemList(),projectPage.getProjectexpenseList());
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "项目-通过id删除")
	@ApiOperation(value="项目-通过id删除", notes="项目-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		projectService.delMain(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "项目-批量删除")
	@ApiOperation(value="项目-批量删除", notes="项目-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.projectService.delBatchMain(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功！");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "项目-通过id查询")
	@ApiOperation(value="项目-通过id查询", notes="项目-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<Project> queryById(@RequestParam(name="id",required=true) String id) {
		Project project = projectService.getById(id);
		if(project==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(project);

	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "项目任务分录通过主表ID查询")
	@ApiOperation(value="项目任务分录主表ID查询", notes="项目任务分录-通主表ID查询")
	@GetMapping(value = "/queryProjectitemByMainId")
	public Result<List<Projectitem>> queryProjectitemListByMainId(@RequestParam(name="id",required=true) String id) {
		List<Projectitem> projectitemList=new ArrayList<>();

		QueryWrapper<Projecttask> queryWrapper=new QueryWrapper<>();
		queryWrapper.eq("projectid",id);
		List<Projecttask> list = projecttaskService.list(queryWrapper);

		for (Projecttask projecttask : list) {
			Projectitem projectitem=new Projectitem();
			projectitem.setTaskname(projecttask.getSubject());
			projectitem.setTaskcate(projecttask.getTaskcate());
			projectitem.setTaskstartdate(projecttask.getStartdate());
			projectitem.setTaskenddate(projecttask.getEnddate());
			projectitem.setTasktag(projecttask.getTags());
			projectitem.setTaskprogress(projecttask.getProgress());
			projectitem.setAssigntoid(projecttask.getAssignedto());
			projectitemList.add(projectitem);
		}
		return Result.OK(projectitemList);
	}
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "项目计划通过主表ID查询")
	@ApiOperation(value="项目计划主表ID查询", notes="项目计划-通主表ID查询")
	@GetMapping(value = "/queryProjectplannedtimeByMainId")
	public Result<List<Projectplannedtime>> queryProjectplannedtimeListByMainId(@RequestParam(name="id",required=true) String id) {
		List<Projectplannedtime> projectplannedtimeList = projectplannedtimeService.selectByMainId(id);
		return Result.OK(projectplannedtimeList);
	}
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "项目销售分录通过主表ID查询")
	@ApiOperation(value="项目销售分录主表ID查询", notes="项目销售分录-通主表ID查询")
	@GetMapping(value = "/queryProjectsalesitemByMainId")
	public Result<List<Projectsalesitem>> queryProjectsalesitemListByMainId(@RequestParam(name="id",required=true) String id) {
		List<Projectsalesitem> projectsalesitemList = projectsalesitemService.selectByMainId(id);
		return Result.OK(projectsalesitemList);
	}
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "项目采购分录通过主表ID查询")
	@ApiOperation(value="项目采购分录主表ID查询", notes="项目采购分录-通主表ID查询")
	@GetMapping(value = "/queryProjectpoitemByMainId")
	public Result<List<Projectpoitem>> queryProjectpoitemListByMainId(@RequestParam(name="id",required=true) String id) {
		List<Projectpoitem> projectpoitemList = projectpoitemService.selectByMainId(id);
		return Result.OK(projectpoitemList);
	}
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "项目费用分录通过主表ID查询")
	@ApiOperation(value="项目费用分录主表ID查询", notes="项目费用分录-通主表ID查询")
	@GetMapping(value = "/queryProjectexpenseByMainId")
	public Result<List<Projectexpense>> queryProjectexpenseListByMainId(@RequestParam(name="id",required=true) String id) {
//		List<Projectexpense> projectexpenseList = projectexpenseService.selectByMainId(id);
		List<Projectexpense> projectexpenseList=new ArrayList<>();
		QueryWrapper<Projectexpenseinfo> queryWrapper=new QueryWrapper<>();
		queryWrapper.eq("projectid",id);
		List<Projectexpenseinfo> list = projectexpenseinfoService.list(queryWrapper);
		for (Projectexpenseinfo projectexpenseinfo : list) {
			Projectexpense projectexpense=new Projectexpense();
			projectexpense.setExpensedate(projectexpenseinfo.getBilldate());
			projectexpense.setTotaltaxinvalue(projectexpenseinfo.getTotaltaxinvalue());
			projectexpense.setTotaltaxexvalue(projectexpenseinfo.getTotaltaxexvalue());
			projectexpense.setTax(projectexpenseinfo.getTotaltax());
			projectexpense.setCreateBy(projectexpense.getCreateBy());
			projectexpense.setAssigntoid(projectexpenseinfo.getAssigntoid());
			projectexpense.setCurrencyid(projectexpense.getCurrencyid());
			projectexpenseList.add(projectexpense);
		}
		return Result.OK(projectexpenseList);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param project
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, Project project) {
      // Step.1 组装查询条件查询数据
      QueryWrapper<Project> queryWrapper = QueryGenerator.initQueryWrapper(project, request.getParameterMap());
      LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

      //配置选中数据查询条件
      String selections = request.getParameter("selections");
      if(oConvertUtils.isNotEmpty(selections)) {
         List<String> selectionList = Arrays.asList(selections.split(","));
         queryWrapper.in("id",selectionList);
      }
      //Step.2 获取导出数据
      List<Project> projectList = projectService.list(queryWrapper);

      // Step.3 组装pageList
      List<ProjectPage> pageList = new ArrayList<ProjectPage>();
      for (Project main : projectList) {
          ProjectPage vo = new ProjectPage();
          BeanUtils.copyProperties(main, vo);
          List<Projectitem> projectitemList = projectitemService.selectByMainId(main.getId());
          vo.setProjectitemList(projectitemList);
          List<Projectplannedtime> projectplannedtimeList = projectplannedtimeService.selectByMainId(main.getId());
          vo.setProjectplannedtimeList(projectplannedtimeList);
          List<Projectsalesitem> projectsalesitemList = projectsalesitemService.selectByMainId(main.getId());
          vo.setProjectsalesitemList(projectsalesitemList);
          List<Projectpoitem> projectpoitemList = projectpoitemService.selectByMainId(main.getId());
          vo.setProjectpoitemList(projectpoitemList);
          List<Projectexpense> projectexpenseList = projectexpenseService.selectByMainId(main.getId());
          vo.setProjectexpenseList(projectexpenseList);
          pageList.add(vo);
      }

      // Step.4 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      mv.addObject(NormalExcelConstants.FILE_NAME, "项目列表");
      mv.addObject(NormalExcelConstants.CLASS, ProjectPage.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("项目数据", "导出人:"+sysUser.getRealname(), "项目"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
    }

    /**
    * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          // 获取上传文件对象
          MultipartFile file = entity.getValue();
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<ProjectPage> list = ExcelImportUtil.importExcel(file.getInputStream(), ProjectPage.class, params);
              for (ProjectPage page : list) {
                  Project po = new Project();
                  BeanUtils.copyProperties(page, po);
                  projectService.saveMain(po, page.getProjectitemList(),page.getProjectplannedtimeList(),page.getProjectsalesitemList(),page.getProjectpoitemList(),page.getProjectexpenseList());
              }
              return Result.OK("文件导入成功！数据行数:" + list.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.OK("文件导入失败！");
    }

}
